package com.sen.ssp.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sen.ssp.exception.SystemExceptionCode.SysCommonCode;
import com.sen.ssp.utils.ConfigManagerUtil;

/**
 * 自定义异常
 * @author sen
 */
public class SspException extends Exception {

	private static final long serialVersionUID = -4640464190051491133L;
	
	/** slf4j logger 日志记录器  */
	private static final Logger LOG = LoggerFactory.getLogger("ssp.exception");
	
	// code
	private String code;
	// 消息
	private String message;
	// 异常原因
	private Throwable cause;
	
	/**
	 * 获取异常code
	 * @return 异常code
	 */
	public String getCode() {
		return code;
	}

	public SspException(String code) {
		this(code, getContent(code));
	}
	
	public SspException(String code, String message) {
		this(code, message, null);
	}
	
	public SspException(String code, Throwable cause) {
		this(code, getContent(code), cause);
	}

	public SspException(String code, String message, Throwable cause) {
		super(String.format("错误编码：%s，信息：%s", code, message), cause);
		this.code = code;
		this.message = message;
		this.cause = cause;
		LOG.error(getLogMessage(), cause);
	}
	
	/**
	 * 获取异常编码对应的异常描述信息，先从classpath:/errorcode.properties配置文件中读取，没有则返回系统公共异常描述信息
	 * @param code 异常编码
	 * @return 异常描述信息
	 */
	protected static String getContent(String code) {
		try {
			return ConfigManagerUtil.getErrorInfo(code);
		} catch (Exception e) {
			return SysCommonCode.EXCEPTION_MSG_READER_ERROR + ":[" + "异常消息读取失败" + "]";
		}
	}

	public String getLogMessage() {
		if (this.cause == null) {
			return String.format("错误编码：%s，信息：%s，异常类型：%s", code, message, this.getClass().getName());
		} else {
			return String.format("错误编码：%s，信息：%s，异常类型：%s，异常源消息：%s", code, message, cause.getClass().getName(),
					cause.getMessage());
		}
	}
}
